package com.hele.sts.dao;

import com.hele.sts.pub.ConnectDB;
import com.hele.sts.pub.SnowFlake;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class XtLogDao {

    private static final Logger logger = LoggerFactory.getLogger(XtLogDao.class);

    private static SnowFlake snowFlake = new SnowFlake(1, 2);

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public boolean insertLog(String logtype,String logname,String userid,String username,String succeed,String message, String className){
        XtLog log = new XtLog();
        log.setClassname(className);
        log.setMethod("execute");
        log.setUserid(userid);
        log.setUsername(username);
        log.setLogtype(logtype);
        log.setLogname(logname);
        log.setCreatetime(new Date(System.currentTimeMillis()));
        log.setSucceed(succeed);
        log.setMessage(message);
        return this.insert(log);
    }

    public boolean insert(XtLog bean){


        Connection conn = null;
        PreparedStatement pstmt = null;
        String sql = null;
        ConnectDB connsyb = null;
        sql = "INSERT INTO XT_LOG VALUES (?,?,?,?,?,?,?,?,?,?)";
        logger.debug(sql);

        try {
            this.jdbcTemplate.update(sql,snowFlake.nextId(),bean.getLogtype(),bean.getLogname(),bean.getUserid(),bean.getUsername(),bean.getClassname(),bean.getMethod(),bean.getCreatetime(),bean.getSucceed(),bean.getMessage());
            return true;
        } catch (DataAccessException e) {
            logger.info("XtUserLoginDao insert", e);
            return false;
        } finally {

        }
    }

    public List<XtLog> list(String logtype, String userid, Date startDate, Date endDate, int pageNo, int pageSize){
        String sql = "SELECT * FROM ( SELECT row_.*, rownum rownum_ FROM (select * from xt_log where 1=1";
        List<Object> params = new ArrayList<>();
        if(StringUtils.isNotBlank(logtype)){
            sql+=" and logtype=?";
            params.add(logtype);
        }
        if(StringUtils.isNotBlank(userid)){
            sql+=" and userid=?";
            params.add(userid);
        }
        if(startDate!=null){
            sql+=" and createtime>=?";
            params.add(startDate);
        }
        if(endDate!=null){
            sql+=" and createtime<=?+1";
            params.add(endDate);
        }
        if(pageNo<=1) {
            pageNo=1;
        }
        if(pageSize==0){
            pageSize=10;
        }
        int startRow = (pageNo-1)*pageSize;
        int endRow = pageNo*pageSize;
        sql = sql + " order by createtime desc ) row_ WHERE rownum <= ?) WHERE rownum_ > ?";
        params.add(endRow);
        params.add(startRow);
        List<XtLog> list = this.jdbcTemplate.query(sql, new RowMapper<XtLog>() {
            @Override
            public XtLog mapRow(ResultSet rs, int rowNum) throws SQLException {
                XtLog xtLog = new XtLog();
                xtLog.setUserid(rs.getString("userid"));
                xtLog.setMessage(rs.getString("message"));
                xtLog.setSucceed(rs.getString("succeed"));
                xtLog.setCreatetime(rs.getTimestamp("createtime"));
                xtLog.setLogname(rs.getString("logname"));
                xtLog.setLogtype(rs.getString("logtype"));
                xtLog.setClassname(rs.getString("classname"));
                xtLog.setMethod(rs.getString("method"));
                return xtLog;
            }
        },params.toArray());
        return list;
    }

    public int count(String logtype, String userid, Date startDate, Date endDate) {
        String sql = "select count(*) from xt_log where 1=1";
        List<Object> params = new ArrayList<>();
        if(StringUtils.isNotBlank(logtype)){
            sql+=" and logtype=?";
            params.add(logtype);
        }
        if(StringUtils.isNotBlank(userid)){
            sql+=" and userid=?";
            params.add(userid);
        }
        if(startDate!=null){
            sql+=" and createtime>=?";
            params.add(startDate);
        }
        if(endDate!=null){
            sql+=" and createtime<=?+1";
            params.add(endDate);
        }

        Integer count = this.jdbcTemplate.queryForObject(sql,params.toArray(),Integer.class);
        return count.intValue();
    }
}
